/**
 * @description {Function} useCallPhone 一键拨打电话
 * @param {string} phone 传入被拨打的手机号
 * @author 花东红
 * @time 2025/3/8
 */
export const useCallPhone = (phone: string) => {
    if (!phone) return;
    const getSystemInfoSync = uni.getSystemInfoSync();
    if (getSystemInfoSync.platform === 'ios') return uni.makePhoneCall({phoneNumber: phone})
    uni.showActionSheet({
        itemList: [phone, '呼叫'],
        success: (resp) => {
            if (resp.tapIndex === 1) uni.makePhoneCall({phoneNumber: phone}).finally()
        }
    })
}
/**
 * @description {Function} useCopyContent 一键复制文本内容
 * @param {string} content 传入需要复制的文本内容
 * @author 花东红
 * @time 2025/3/8
 */
export const useCopyContent = (content: string) => {
    if (!content) return;
    uni.setClipboardData({
        data: content,
        success: () => {
            uni.showToast({title: '复制成功', icon: 'none'}).finally()
        }
    });
}
/**
 * @description {Function} useToast
 * @author 花东红
 * @time 2025/3/8
 * @param props showToast 参数
 * @param callback 回调函数
 */
export const useToast = (props: Record<string, any>, callback?: Function) => {
    const {message = '', type = 'none', duration = 3000} = props
    uni.showToast({
        title: message,
        icon: type,
        duration: duration,
        success: () => {
            if (callback) return callback()
        }
    })
}
/**
 * @description {Function} useModal
 * @author 花东红
 * @time 2025/3/8
 * @param props showModal 参数
 * @param callback 回调函数
 */
export const useModal = (props: Record<string, any>, callback?: Function) => {
    const {
        title = '操作失败',
        message = '',
        confirmColor = '#FF5500',
        cancelColor = '',
        showCancel = false,
        confirmText = '确定',
        cancelText = '取消'
    } = props
    uni.showModal({
        title,
        content: message,
        confirmColor,
        cancelColor,
        showCancel,
        confirmText,
        cancelText,
        success: (resp) => {
            if (callback) return callback(resp.confirm)
        }
    });
}
/**
 * @description {Function} useLoading
 * @author 花东红
 * @time 2025/3/8
 * @param message
 */
export const useLoading = (message?: string) => {
    uni.showLoading({
        title: message || '加载中...'
    }).finally()
}
/**
 * @description {Function} useCloseLoading
 * @author 花东红
 * @time 2025/3/8
 */
export const useCloseLoading = () => {
    uni.hideLoading()
}
/**
 * @description {Function} useSetStorageSync
 * @author 花东红
 * @time 2025/3/8
 */
export const useSetStorageSync = (key: string, data: any) => {
    if (!key) return;
    uni.setStorageSync(key, data)
}
/**
 * @description {Function} useGetStorageSync
 * @author 花东红
 * @time 2025/3/8
 */
export const useGetStorageSync = (key: string) => {
    if (!key) return;
    return uni.getStorageSync(key) ?? ''
}
/**
 * @description {Function} useRemoveStorageSync
 * @author 花东红
 * @time 2025/3/8
 */
export const useRemoveStorageSync = (key: string) => {
    if (!key) return;
    uni.removeStorageSync(key)
}
/**
 * @description {Function} useClearStorageSync
 * @author 花东红
 * @time 2025/3/8
 */
export const useClearStorageSync = () => {
    uni.clearStorageSync()
}
/**
 * @description {Function} useGetSystemInfoSyncPlatform 获取当前运行平台
 * @return mp-weixin | web | app | mp-alipay | mp-baidu | mp-toutiao | mp-qq | mp-lark | mp-kuaishou | mp-jd
 * @author 花东红
 * @time 2025/3/8
 */
export const useGetSystemInfoSyncPlatform = () => {
    return (uni.getAppBaseInfo() as UniNamespace.GetSystemInfoResult).uniPlatform
}
/**
 * @description {Function} useWChartMiniProgramsPlatform 获取微信小程序当前运行环境,只能在微信小程序中使用
 * @return develop | trial | release
 * @author 花东红
 * @time 2025/3/8
 */
export const useWChartMiniProgramsPlatform = () => {
    return uni.getAccountInfoSync().miniProgram.envVersion
}
/**
 * @description {Function} useReLaunch 关闭所有页面，打开到应用内的某个页面
 * @author 花东红
 * @time 2025/3/8E
 */
export const useReLaunch = (url: string, params?: Record<string, any>) => {
    if (params && Object.prototype.toString.call(params) !== '[object Object]') return
    if (!params || !Object.keys(params).length) {
        uni.reLaunch({url}).finally()
    } else {
        uni.reLaunch({url: `${url}?data=${encodeURIComponent(JSON.stringify(params))}`}).finally()
    }
}
/**
 * @description {Function} useRedirectTo 关闭当前页面，跳转到应用内的某个页面
 * @author 花东红
 * @time 2025/3/8
 */
export const useRedirectTo = (url: string, params?: Record<string, any>) => {
    if (params && Object.prototype.toString.call(params) !== '[object Object]') return
    if (!params || !Object.keys(params)) {
        uni.redirectTo({url}).finally()
    } else {
        uni.redirectTo({url: `${url}?data=${encodeURIComponent(JSON.stringify(params))}`}).finally()
    }
}
/**
 * @description {Function} useNavigateTo 保留当前页面，跳转到应用内的某个页面
 * @author 花东红
 * @time 2025/3/8
 */
export const useNavigateTo = (url: string, params?: Record<string, any>) => {
    if (params && Object.prototype.toString.call(params) !== '[object Object]') return
    if (!params || !Object.keys(params).length) {
        uni.navigateTo({url}).finally()
    } else {
        uni.navigateTo({url: `${url}?data=${encodeURIComponent(JSON.stringify(params))}`}).finally()
    }
}
/**
 * @description {Function} useSwitchTab 跳转到tabBar页面，并关闭其他所有非tabBar页面
 * @author 花东红
 * @time 2025/3/8
 */
export const useSwitchTab = (url: string, params?: Record<string, any>) => {
    if (params && Object.prototype.toString.call(params) !== '[object Object]') return
    if (!params || !Object.keys(params).length) {
        uni.switchTab({url}).finally()
    } else {
        uni.switchTab({url: `${url}?data=${encodeURIComponent(JSON.stringify(params))}`}).finally()
    }
}
/**
 * @description {Function} useParseNavigateQuery 解析路由参数（在onLoad钩子中调用传入onLoad形参）
 * @author 花东红
 * @time 2025/3/8
 */
export const useParseNavigateQuery = (params: Record<string, any>, key?: string) => {
    if (!Object.keys(params).length) return {}
    return JSON.parse(decodeURIComponent(params[key ?? 'data']))
}
/**
 * @description {Function} useGenerateUUID 生成随机UUID
 * @author 花东红
 * @time 2025/3/8
 */
export const useGenerateUUID = () => {
    const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4())
}
/**
 * @description {Function} usePullUpPayment 拉起支付（兼容支付宝和微信）
 * @param {UniNamespace.RequestPaymentOptions & { trade_no: string }} data 支付所需要的参数
 * @remark 微信支付需要参数 timeStamp, nonceStr, package, signType, paySign
 * @remark 支付宝需要参数 trade_no
 * @author 花东红
 * @time 2025/3/8
 */
export const usePullUpPayment = (data: UniNamespace.RequestPaymentOptions & { trade_no: string }) => {
    const {trade_no, timeStamp, nonceStr, package: packageStr, signType, paySign} = data
    return new Promise((resolve, reject) => {
        uni.requestPayment({
            // #ifdef MP-ALIPAY
            provider: 'alipay',
            orderInfo: trade_no,
            // #endif
            // #ifdef MP-WEIXIN
            // @ts-ignore
            provider: 'wxpay',
            timeStamp,
            nonceStr,
            package: packageStr,
            signType,
            paySign,
            // #endif
            success: (resp) => {
                // #ifdef MP-ALIPAY
                if (resp.resultCode === 9000) return resolve(true)
                uni.showModal({
                    content: resp.memo ? resp.memo : "支付未完成",
                    confirmColor: '#FF5500',
                    showCancel: false
                }).finally()
                reject(false)
                // #endif
                // #ifdef MP-WEIXIN
                resolve(true)
                // #endif
            },
            fail: () => {
                uni.showModal({
                    content: "支付未完成，请重新支付。",
                    confirmColor: '#FF5500',
                    showCancel: false,
                }).finally()
                reject(false)
            }
        })
    })
}
